<template>
  <div class="change-phone-page">
    <Header :scroll="scroll" />

    <!-- 换绑手机号内容区域 -->
    <div class="change-phone-content">
      <div class="container">
        <div class="change-phone-wrapper">
          <!-- 左侧品牌信息 -->
          <div class="brand-section">
            <div class="brand-content">
              <img src="@/assets/logo-full.png" alt="六堡茶" class="brand-logo" />
              <h2 class="brand-title">更换手机号</h2>
              <p class="brand-desc">为了您的账号安全，请按照以下步骤更换手机号</p>
              <div class="steps-indicator">
                <div class="step" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
                  <div class="step-number">1</div>
                  <span class="step-text">验证当前手机</span>
                </div>
                <div class="step" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
                  <div class="step-number">2</div>
                  <span class="step-text">绑定新手机</span>
                </div>
                <div class="step" :class="{ active: currentStep >= 3, completed: currentStep > 3 }">
                  <div class="step-number">3</div>
                  <span class="step-text">完成更换</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧表单区域 -->
          <div class="form-section">
            <div class="form-container">
              <!-- 步骤1：验证当前手机号 -->
              <div v-if="currentStep === 1" class="step-content">
                <div class="form-header">
                  <h3 class="form-title">验证当前手机号</h3>
                  <p class="form-subtitle">验证码将发送至您当前绑定的手机号 {{ maskPhone(currentPhone) }}</p>
                </div>

                <el-form ref="currentPhoneFormRef" :model="currentPhoneForm" :rules="currentPhoneRules" class="change-form">
                  <el-form-item prop="verifyCode">
                    <div class="verify-code-wrapper">
                      <el-input
                        v-model="currentPhoneForm.verifyCode"
                        placeholder="请输入6位验证码"
                        size="large"
                        prefix-icon="Message"
                        clearable
                        maxlength="6" />
                      <el-button class="verify-btn" :disabled="step1Countdown > 0" @click="sendCurrentPhoneCode">
                        {{ step1Countdown > 0 ? `${step1Countdown}s后重发` : '获取验证码' }}
                      </el-button>
                    </div>
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" size="large" class="submit-btn" :loading="loading" @click="handleCurrentPhoneSubmit">
                      {{ loading ? '验证中...' : '下一步' }}
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 步骤2：绑定新手机号 -->
              <div v-if="currentStep === 2" class="step-content">
                <div class="form-header">
                  <h3 class="form-title">绑定新手机号</h3>
                  <p class="form-subtitle">请输入您要绑定的新手机号码</p>
                </div>

                <el-form ref="newPhoneFormRef" :model="newPhoneForm" :rules="newPhoneRules" class="change-form">
                  <el-form-item prop="newPhone">
                    <el-input
                      v-model="newPhoneForm.newPhone"
                      placeholder="请输入新手机号"
                      size="large"
                      prefix-icon="Phone"
                      clearable
                      maxlength="11" />
                  </el-form-item>

                  <el-form-item prop="verifyCode">
                    <div class="verify-code-wrapper">
                      <el-input
                        v-model="newPhoneForm.verifyCode"
                        placeholder="请输入6位验证码"
                        size="large"
                        prefix-icon="Message"
                        clearable
                        maxlength="6" />
                      <el-button class="verify-btn" :disabled="step2Countdown > 0 || !isValidPhone(newPhoneForm.newPhone)" @click="sendNewPhoneCode">
                        {{ step2Countdown > 0 ? `${step2Countdown}s后重发` : '获取验证码' }}
                      </el-button>
                    </div>
                  </el-form-item>

                  <el-form-item>
                    <div class="button-group">
                      <el-button size="large" @click="goBack">上一步</el-button>
                      <el-button type="primary" size="large" class="submit-btn" :loading="loading" @click="handleNewPhoneSubmit">
                        {{ loading ? '绑定中...' : '确认绑定' }}
                      </el-button>
                    </div>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 步骤3：完成提示 -->
              <div v-if="currentStep === 3" class="step-content success-content">
                <div class="success-icon">✓</div>
                <h3 class="success-title">手机号更换成功！</h3>
                <p class="success-desc">您的手机号已成功更换为：{{ newPhoneForm.newPhone }}</p>
                <el-button type="primary" size="large" class="submit-btn" @click="goToProfile"> 返回个人中心 </el-button>
              </div>

              <!-- 返回链接 -->
              <div v-if="currentStep < 3" class="form-footer">
                <span class="back-text">不想更换了？</span>
                <router-link to="/profile" class="back-link">返回个人中心</router-link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref, reactive, onMounted, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import { useUserStore } from '@/stores/user.js'
  import apiUser from '@/api/modules/user'

  const router = useRouter()
  const userStore = useUserStore()
  const { proxy } = getCurrentInstance()
  const scroll = ref(false)
  const currentPhoneFormRef = ref()
  const newPhoneFormRef = ref()
  const loading = ref(false)
  const currentStep = ref(1)
  const step1Countdown = ref(0)
  const step2Countdown = ref(0)

  const currentPhone = ref('') // 从用户信息获取
  const userInfo = computed(() => userStore.userInfo)

  // 监听滚动
  onMounted(() => {
    window.addEventListener('scroll', () => {
      scroll.value = window.scrollY > 0
    })

    // 获取当前用户手机号
    getCurrentUserPhone()
  })

  // 表单数据
  const currentPhoneForm = reactive({
    verifyCode: '',
  })

  const newPhoneForm = reactive({
    newPhone: '',
    verifyCode: '',
  })

  // 手机号脱敏显示
  const maskPhone = (phone) => {
    if (!phone) return ''
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
  }

  // 验证手机号格式
  const isValidPhone = (phone) => {
    const phoneRegex = /^1[3-9]\d{9}$/
    return phoneRegex.test(phone)
  }

  // 自定义验证函数
  const validatePhone = (rule, value, callback) => {
    if (!isValidPhone(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }

  const validateVerifyCode = (rule, value, callback) => {
    if (!value || value.length !== 6) {
      callback(new Error('验证码为6位数字'))
    } else {
      callback()
    }
  }

  // 表单验证规则
  const currentPhoneRules = {
    verifyCode: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { validator: validateVerifyCode, trigger: 'blur' },
    ],
  }

  const newPhoneRules = {
    newPhone: [
      { required: true, message: '请输入新手机号', trigger: 'blur' },
      { validator: validatePhone, trigger: 'blur' },
    ],
    verifyCode: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { validator: validateVerifyCode, trigger: 'blur' },
    ],
  }

  // 获取当前用户手机号
  const getCurrentUserPhone = async () => {
    try {
      currentPhone.value = proxy.$decryptAES(userInfo.value.mobile)
    } catch (error) {
      console.error('获取用户信息失败:', error)
      ElMessage.error('获取用户信息失败')
    }
  }

  // 发送当前手机验证码
  const sendCurrentPhoneCode = async () => {
    try {
      // 调用发送验证码API
      // await sendSmsCode({ phone: currentPhone.value, type: 'verify_current' })
      apiUser.GetVerifyCode({ mobile: currentPhone.value }).then(async (res) => {
        ElMessage.success('验证码已发送')
        startCountdown('step1')
      })
    } catch (error) {
      ElMessage.error('发送失败，请重试')
    }
  }

  // 发送新手机验证码
  const sendNewPhoneCode = async () => {
    if (!isValidPhone(newPhoneForm.newPhone)) {
      ElMessage.warning('请先输入正确的手机号')
      return
    }

    try {
      // 调用发送验证码API
      // await sendSmsCode({ phone: newPhoneForm.newPhone, type: 'bind_new' })
      apiUser.GetVerifyCode2({ mobile: newPhoneForm.newPhone }).then(async (res) => {
        ElMessage.success('验证码已发送')
        startCountdown('step2')
      })
    } catch (error) {
      ElMessage.error('发送失败，请重试')
    }
  }

  // 开始倒计时
  const startCountdown = (step) => {
    const countdownKey = step === 'step1' ? 'step1Countdown' : 'step2Countdown'
    const countdownRef = step === 'step1' ? step1Countdown : step2Countdown

    countdownRef.value = 60
    const timer = setInterval(() => {
      countdownRef.value--
      if (countdownRef.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  }

  // 处理当前手机号验证
  const handleCurrentPhoneSubmit = async () => {
    if (!currentPhoneFormRef.value) return

    try {
      const valid = await currentPhoneFormRef.value.validate()
      if (!valid) return

      loading.value = true

      // API调用验证验证码
      apiUser.VerifyCurrentPhone({ mobile: currentPhone.value, captcha: currentPhoneForm.verifyCode }).then(async (res) => {
        ElMessage.success('验证成功')
        // 进入下一步
        currentStep.value = 2
      })
    } catch (error) {
      console.error('验证失败:', error)
      ElMessage.error('验证码错误或已过期')
    } finally {
      loading.value = false
    }
  }

  // 处理新手机号绑定
  const handleNewPhoneSubmit = async () => {
    if (!newPhoneFormRef.value) return

    try {
      const valid = await newPhoneFormRef.value.validate()
      if (!valid) return

      // 检查新手机号是否与当前手机号相同
      if (newPhoneForm.newPhone === currentPhone.value) {
        ElMessage.warning('新手机号不能与当前手机号相同')
        return
      }

      loading.value = true

      // API调用更换手机号
      const saveData = {
        info: {
          mobile: newPhoneForm.newPhone,
        },
        verifyMobile: newPhoneForm.newPhone,
        captcha: newPhoneForm.verifyCode,
      }
      apiUser.updateUserBaseInfo(saveData).then(async (res) => {
        ElMessage.success('手机号更换成功！')
        // 进入完成步骤
        currentStep.value = 3
        userInfo.value.mobile = proxy.$encryptAES(newPhoneForm.newPhone)
        userInfo.value.mobile_hidden = proxy.$hidePhoneNumber(newPhoneForm.newPhone)
        userStore.updateUserInfo(userInfo.value)
      })
    } catch (error) {
      console.error('更换失败:', error)
      ElMessage.error('手机号更换失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }

  // 返回上一步
  const goBack = () => {
    if (currentStep.value > 1) {
      currentStep.value--
    }
  }

  // 返回个人中心
  const goToProfile = () => {
    router.push('/profile')
  }
</script>

<style scoped>
  .change-phone-page {
    min-height: 100vh;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  }

  .change-phone-content {
    padding: 60px 0;
    min-height: calc(100vh - 200px);
    display: flex;
    align-items: center;
  }

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }

  .change-phone-wrapper {
    display: flex;
    background: white;
    border-radius: 16px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    min-height: 600px;
  }

  /* 左侧品牌区域 */
  .brand-section {
    flex: 1;
    background: linear-gradient(135deg, #1c705e 0%, #2d8a6e 100%);
    color: white;
    padding: 60px 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .brand-content {
    text-align: center;
    max-width: 400px;
  }

  .brand-logo {
    width: 120px;
    height: auto;
    margin-bottom: 30px;
  }

  .brand-title {
    font-size: 32px;
    font-weight: 600;
    margin-bottom: 16px;
  }

  .brand-desc {
    font-size: 16px;
    margin-bottom: 40px;
    opacity: 0.9;
    line-height: 1.6;
  }

  /* 步骤指示器 */
  .steps-indicator {
    display: flex;
    flex-direction: column;
    gap: 30px;
  }

  .step {
    display: flex;
    align-items: center;
    gap: 15px;
    opacity: 0.6;
    transition: all 0.3s ease;
  }

  .step.active {
    opacity: 1;
  }

  .step.completed {
    opacity: 0.8;
  }

  .step-number {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    font-weight: 600;
  }

  .step.active .step-number {
    background: white;
    color: #1c705e;
  }

  .step.completed .step-number {
    background: #4ade80;
    color: white;
  }

  .step-text {
    font-size: 14px;
    font-weight: 500;
  }

  /* 右侧表单区域 */
  .form-section {
    flex: 1;
    padding: 60px 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .form-container {
    width: 100%;
    max-width: 400px;
  }

  .step-content {
    min-height: 300px;
  }

  .form-header {
    text-align: center;
    margin-bottom: 40px;
  }

  .form-title {
    font-size: 28px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }

  .form-subtitle {
    color: #666;
    font-size: 14px;
  }

  .change-form {
    margin-bottom: 30px;
  }

  .change-form .el-form-item {
    margin-bottom: 24px;
  }

  /* 验证码输入区域 */
  .verify-code-wrapper {
    display: flex;
    gap: 12px;
  }

  .verify-code-wrapper .el-input {
    flex: 1;
  }

  .verify-btn {
    width: 120px;
    height: 40px;
    font-size: 14px;
  }

  .button-group {
    display: flex;
    gap: 12px;
  }

  .button-group .el-button {
    flex: 1;
    height: 48px;
    font-size: 16px;
  }

  .submit-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 600;
    background: #1c705e;
    border-color: #1c705e;
  }

  /* 在button-group中的submit-btn不使用width: 100% */
  .button-group .submit-btn {
    width: auto;
  }

  .submit-btn:hover {
    background: #2d8a6e;
    border-color: #2d8a6e;
  }

  /* 成功页面 */
  .success-content {
    text-align: center;
    padding: 40px 0;
  }

  .success-icon {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: #4ade80;
    color: white;
    font-size: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 30px;
  }

  .success-title {
    font-size: 24px;
    color: #333;
    margin-bottom: 16px;
  }

  .success-desc {
    color: #666;
    margin-bottom: 40px;
    line-height: 1.6;
  }

  .form-footer {
    text-align: center;
    font-size: 14px;
    color: #666;
  }

  .back-link {
    color: #1c705e;
    text-decoration: none;
    font-weight: 600;
    margin-left: 8px;
  }

  .back-link:hover {
    text-decoration: underline;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .change-phone-wrapper {
      flex-direction: column;
      margin: 20px;
    }

    .brand-section {
      padding: 40px 20px;
    }

    .form-section {
      padding: 40px 20px;
    }

    .brand-title {
      font-size: 24px;
    }

    .form-title {
      font-size: 24px;
    }

    .steps-indicator {
      flex-direction: row;
      justify-content: center;
      gap: 30px;
    }

    .step {
      flex-direction: column;
      gap: 8px;
    }

    .step-text {
      font-size: 12px;
    }

    .button-group {
      flex-direction: column;
    }

    .verify-code-wrapper {
      flex-direction: column;
    }

    .verify-btn {
      width: 100%;
    }
  }

  @media (max-width: 480px) {
    .change-phone-content {
      padding: 20px 0;
    }

    .container {
      padding: 0 10px;
    }

    .brand-section,
    .form-section {
      padding: 30px 15px;
    }
  }
</style>
